<?php
/***************************************************************************
*                            Dolphin Smart Community Builder
*                              -------------------
*     begin                : Mon Mar 23 2006
*     copyright            : (C) 2007 BoonEx School
*     website              : http://www.boonex.com
* This file is part of Dolphin - Smart Community Builder
*
* Dolphin is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the
* License, or  any later version.
*
* Dolphin is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
* You should have received a copy of the GNU General Public License along with Dolphin,
* see license.txt file; if not, write to marketing@boonex.com
***************************************************************************/

function modzzz_schools_import ($sClassPostfix, $aModuleOverwright = array()) {
    global $aModule;
    $a = $aModuleOverwright ? $aModuleOverwright : $aModule;
    if (!$a || $a['uri'] != 'schools') {
        $oMain = BxDolModule::getInstance('BxSchoolsModule');
        $a = $oMain->_aModule;
    }
    bx_import ($sClassPostfix, $a) ;
}

bx_import('BxDolPaginate');
bx_import('BxDolAlerts');
bx_import('BxDolTwigModule');

define ('BX_SCHOOLS_PHOTOS_CAT', 'Schools');
define ('BX_SCHOOLS_PHOTOS_TAG', 'schools');

define ('BX_SCHOOLS_VIDEOS_CAT', 'Schools');
define ('BX_SCHOOLS_VIDEOS_TAG', 'schools');

define ('BX_SCHOOLS_SOUNDS_CAT', 'Schools');
define ('BX_SCHOOLS_SOUNDS_TAG', 'schools');

define ('BX_SCHOOLS_FILES_CAT', 'Schools');
define ('BX_SCHOOLS_FILES_TAG', 'schools');

define ('BX_SCHOOLS_MAX_FANS', 10000);

/*
 * Schools module
 *
 * This module allow users to create user's schools, 
 * users can rate, comment and discuss school.
 * School can have photos, videos, sounds and files, uploaded
 * by school's fans and/or admins.
 *
 * 
 *
 * Profile's Wall:
 * 'add school' event is displayed in profile's wall
 *
 *
 *
 * Spy:
 * The following qactivity is displayed for content_activity:
 * add - new school was created
 * change - school was chaned
 * join - somebody joined school
 * rate - somebody rated school
 * commentPost - somebody posted comment in school
 *
 *
 *
 * Memberships/ACL:
 * schools view school - BX_SCHOOLS_VIEW_SCHOOL
 * schools browse - BX_SCHOOLS_BROWSE
 * schools search - BX_SCHOOLS_SEARCH
 * schools add school - BX_SCHOOLS_ADD_SCHOOL
 * schools comments delete and edit - BX_SCHOOLS_COMMENTS_DELETE_AND_EDIT
 * schools edit any school - BX_SCHOOLS_EDIT_ANY_SCHOOL
 * schools delete any school - BX_SCHOOLS_DELETE_ANY_SCHOOL
 * schools mark as featured - BX_SCHOOLS_MARK_AS_FEATURED
 * schools approve schools - BX_SCHOOLS_APPROVE_SCHOOLS
 * schools broadcast message - BX_SCHOOLS_BROADCAST_MESSAGE
 *
 * 
 *
 * Service methods:
 *
 * Homepage block with different schools
 * @see BxSchoolsModule::serviceHomepageBlock
 * BxDolService::call('schools', 'homepage_block', array());
 *
 * Profile block with user's schools
 * @see BxSchoolsModule::serviceProfileBlock
 * BxDolService::call('schools', 'profile_block', array($iProfileId));
 *
 * School's forum permissions (for internal usage only)
 * @see BxSchoolsModule::serviceGetForumPermission
 * BxDolService::call('schools', 'get_forum_permission', array($iMemberId, $iForumId));
 *
 * Member menu item for schools (for internal usage only)
 * @see BxSchoolsModule::serviceGetMemberMenuItem
 * BxDolService::call('schools', 'get_member_menu_item', array());
 *
 *
 *
 * Alerts:
 * Alerts type/unit - 'modzzz_schools'
 * The following alerts are rised
 *
 *  join - user joined a school
 *      $iObjectId - school id
 *      $iSenderId - joined user
 *
 *  join_request - user want to join a school
 *      $iObjectId - school id
 *      $iSenderId - user id which want to join a school
 *
 *  join_reject - user was rejected to join a school
 *      $iObjectId - school id
 *      $iSenderId - regected user id
 *
 *  fan_remove - fan was removed from a school
 *      $iObjectId - school id
 *      $iSenderId - fan user if which was removed from admins
 *
 *  fan_become_admin - fan become school's admin
 *      $iObjectId - school id
 *      $iSenderId - nerw school's fan user id
 *
 *  admin_become_fan - school's admin become regular fan
 *      $iObjectId - school id
 *      $iSenderId - school's admin user id which become regular fan
 *
 *  join_confirm - school's admin confirmed join request
 *      $iObjectId - school id
 *      $iSenderId - condirmed user id
 *
 *  add - new school was added
 *      $iObjectId - school id
 *      $iSenderId - creator of a school
 *      $aExtras['Status'] - status of added school
 *
 *  change - school's info was changed
 *      $iObjectId - school id
 *      $iSenderId - editor user id
 *      $aExtras['Status'] - status of changed school
 *
 *  delete - school was deleted
 *      $iObjectId - school id
 *      $iSenderId - deleter user id
 *
 *  mark_as_featured - school was marked/unmarked as featured
 *      $iObjectId - school id
 *      $iSenderId - performer id
 *      $aExtras['Featured'] - 1 - if school was marked as featured and 0 - if school was removed from featured 
 *
 */
class BxSchoolsModule extends BxDolTwigModule {

    var $_oPrivacy;
    var $_aQuickCache = array ();

    function BxSchoolsModule(&$aModule) {

        parent::BxDolTwigModule($aModule);        
        $this->_sFilterName = 'modzzz_schools_filter';
        $this->_sPrefix = 'modzzz_schools';

        bx_import ('Privacy', $aModule);
        $this->_oPrivacy = new BxSchoolsPrivacy($this);
 
		if($_GET['ajax']=='state')
		{
			$sCountryCode = $_GET['country'];
			echo $this->_oDb->getStateOptions($sCountryCode);
			exit;
		}		
  
        $GLOBALS['oBxSchoolsModule'] = &$this;
    }

    function actionHome () {
        parent::_actionHome(_t('_modzzz_schools_page_title_home'));
    }

    function actionFiles ($sUri) {
        parent::_actionFiles ($sUri, _t('_modzzz_schools_page_title_files'));
    }

    function actionSounds ($sUri) {
        parent::_actionSounds ($sUri, _t('_modzzz_schools_page_title_sounds'));
    }

    function actionVideos ($sUri) {
        parent::_actionVideos ($sUri, _t('_modzzz_schools_page_title_videos'));
    }

    function actionPhotos ($sUri) {
        parent::_actionPhotos ($sUri, _t('_modzzz_schools_page_title_photos'));
    }

    function actionComments ($sUri) {
        parent::_actionComments ($sUri, _t('_modzzz_schools_page_title_comments'));
    }

    function actionBrowseFans ($sUri) {
        parent::_actionBrowseFans ($sUri, 'isAllowedViewFans', 'getFansBrowse', $this->_oDb->getParam('modzzz_schools_perpage_browse_fans'), 'browse_fans/', _t('_modzzz_schools_page_title_fans'));
    }

    function actionBrowseStudents ($sUri) {
        parent::_actionBrowseFans ($sUri, 'isAllowedViewFans', 'getStudentsBrowse', $this->_oDb->getParam('modzzz_schools_perpage_browse_fans'), 'browse_students/', _t('_modzzz_schools_page_title_students'));
    }

    function actionBrowseAlumni ($sUri) {
        parent::_actionBrowseFans ($sUri, 'isAllowedViewFans', 'getAlumniBrowse', $this->_oDb->getParam('modzzz_schools_perpage_browse_fans'), 'browse_alumni/', _t('_modzzz_schools_page_title_alumni'));
    }

    function actionView ($sUri) {
        parent::_actionView ($sUri, _t('_modzzz_schools_msg_pending_approval'));
    }

    function actionUploadPhotos ($sUri) {        
        parent::_actionUploadMedia ($sUri, 'isAllowedUploadPhotos', 'images', array ('images_choice', 'images_upload'), _t('_modzzz_schools_page_title_upload_photos'));
    }

    function actionUploadVideos ($sUri) {
        parent::_actionUploadMedia ($sUri, 'isAllowedUploadVideos', 'videos', array ('videos_choice', 'videos_upload'), _t('_modzzz_schools_page_title_upload_videos'));
    }

    function actionUploadSounds ($sUri) {
        parent::_actionUploadMedia ($sUri, 'isAllowedUploadSounds', 'sounds', array ('sounds_choice', 'sounds_upload'), _t('_modzzz_schools_page_title_upload_sounds')); 
    }

    function actionUploadFiles ($sUri) {
        parent::_actionUploadMedia ($sUri, 'isAllowedUploadFiles', 'files', array ('files_choice', 'files_upload'), _t('_modzzz_schools_page_title_upload_files')); 
    }
 
    function _getInviteParams ($aDataEntry, $aInviter) {
        
		if($aInviter){ 
			$sInviterNickName = ($aInviter['FirstName']) ? $aInviter['FirstName'] .' '. $aInviter['LastName'] : $aInviter['NickName'];
		}else{
			$sInviterNickName = _t('_modzzz_referral_someone'); 
		}

		return array (
                'SchoolName' => $aDataEntry['title'],
                'SchoolLocation' => _t($GLOBALS['aPreValues']['Country'][$aDataEntry['country']]['LKey']) . (trim($aDataEntry['city']) ? ', '.$aDataEntry['city'] : '') . ', ' . $aDataEntry['zip'],
                'SchoolUrl' => BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'view/' . $aDataEntry['uri'].'?&idRef='.$aInviter['ID'].'&idCode='.time(), 
                'InviterUrl' => $aInviter ? getProfileLink($aInviter['ID']) : 'javascript:void(0);',
                'InviterNickName' => $sInviterNickName,
                'InvitationText' => stripslashes(strip_tags($_REQUEST['inviter_text'])),
		'Item' => 'modzzz_schools',
		'ItemID' => $aDataEntry['id'], 
		'Ref' => $aInviter['ID'], 
		'Code' => time(), 
            );        
    }  
  
    function actionAdd () {
        parent::_actionAdd (_t('_modzzz_schools_page_title_add'));
    }

    function actionEdit ($iEntryId) {
        parent::_actionEdit ($iEntryId, _t('_modzzz_schools_page_title_edit'));
    }

    function actionDelete ($iEntryId) {
        parent::_actionDelete ($iEntryId, _t('_modzzz_schools_msg_school_was_deleted'));
    }

    function actionMarkFeatured ($iEntryId) {
        parent::_actionMarkFeatured ($iEntryId, _t('_modzzz_schools_msg_added_to_featured'), _t('_modzzz_schools_msg_removed_from_featured'));
    }
 
    function actionSharePopup ($iEntryId) {
        parent::_actionSharePopup ($iEntryId, _t('_modzzz_schools_caption_share_school'));
    }

    function actionManageFansPopup ($iEntryId) {
        parent::_actionManageFansPopup ($iEntryId, _t('_modzzz_schools_caption_manage_fans'), 'getAllFans', 'isAllowedManageFans', 'isAllowedManageAdmins', BX_SCHOOLS_MAX_FANS);
    }

    function _actionManageFansPopup ($iEntryId, $sTitle, $sFuncGetFans = 'getFans', $sFuncIsAllowedManageFans = 'isAllowedManageFans', $sFuncIsAllowedManageAdmins = 'isAllowedManageAdmins', $iMaxFans = 1000) {

        $iEntryId = (int)$iEntryId;
        if (!($aDataEntry = $this->_oDb->getEntryByIdAndOwner ($iEntryId, 0, true))) {
            echo $GLOBALS['oFunctions']->transBox(MsgBox(_t('_Empty')));
            exit;
        }

        if (!$this->$sFuncIsAllowedManageFans($aDataEntry)) {
            echo $GLOBALS['oFunctions']->transBox(MsgBox(_t('_Access denied')));
            exit;
        }

        $aProfiles = array ();
        $iNum = $this->_oDb->$sFuncGetFans($aProfiles, $iEntryId, true, 0, $iMaxFans);
        if (!$iNum) {
            echo $GLOBALS['oFunctions']->transBox(MsgBox(_t('_Empty')));
            exit;
        }

        $sActionsUrl = BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . "view/" . $aDataEntry[$this->_oDb->_sFieldUri] . '?ajax_action=';
        $aButtons = array (
            array (
                'type' => 'submit',
                'name' => 'fans_remove',
                'value' => _t('_sys_btn_fans_remove'),
                'onclick' => "onclick=\"getHtmlData('sys_manage_items_manage_fans_content', '{$sActionsUrl}remove&ids=' + sys_manage_items_get_manage_fans_ids(), false, 'post'); return false;\"",
            ),
        );

        if ($this->$sFuncIsAllowedManageAdmins($aDataEntry)) {

            $aButtons = array_merge($aButtons, array (
                array (
                    'type' => 'submit',
                    'name' => 'fans_add_to_admins',
                    'value' => _t('_sys_btn_fans_add_to_admins'),
                    'onclick' => "onclick=\"getHtmlData('sys_manage_items_manage_fans_content', '{$sActionsUrl}add_to_admins&ids=' + sys_manage_items_get_manage_fans_ids(), false, 'post'); return false;\"",
                ),
                array (
                    'type' => 'submit',
                    'name' => 'fans_move_admins_to_fans',
                    'value' => _t('_sys_btn_fans_move_admins_to_fans'),
                    'onclick' => "onclick=\"getHtmlData('sys_manage_items_manage_fans_content', '{$sActionsUrl}admins_to_fans&ids=' + sys_manage_items_get_manage_fans_ids(), false, 'post'); return false;\"",
                ),            
            ));
        };
        bx_import ('BxTemplSearchResult');
        $sControl = BxTemplSearchResult::showAdminActionsPanel('sys_manage_items_manage_fans', $aButtons, 'sys_fan_unit');

        $aVarsContent = array (            
            'suffix' => 'manage_fans',
            'content' => $this->_profilesEdit($aProfiles, false, $aDataEntry),
            'control' => $sControl,
        );
        $aVarsPopup = array (
            'title' => $sTitle,
            'content' => $this->_oTemplate->parseHtmlByName('manage_items_form', $aVarsContent),
        );        
        echo $GLOBALS['oFunctions']->transBox($this->_oTemplate->parseHtmlByName('popup', $aVarsPopup), true);
        exit;
    }

    function actionTags() {
        parent::_actionTags (_t('_modzzz_schools_page_title_tags'));
    }    

    function actionCategories() {
        parent::_actionCategories (_t('_modzzz_schools_page_title_categories'));
    }    

    function actionDownload ($iEntryId, $iMediaId) {

        $aFileInfo = $this->_oDb->getMedia ((int)$iEntryId, (int)$iMediaId, 'files');

        if (!$aFileInfo || !($aDataEntry = $this->_oDb->getEntryByIdAndOwner((int)$iEntryId, 0, true))) {
            $this->_oTemplate->displayPageNotFound ();
            exit;
        }

        if (!$this->isAllowedView ($aDataEntry)) {
            $this->_oTemplate->displayAccessDenied ();
            exit;
        }

        parent::_actionDownload($aFileInfo, 'media_id');
    }

    // ================================== external actions


     /**
     * forum permissions
     * @param $iMemberId profile id
     * @param $iForumId forum id
     * @return array with permissions
     */ 
    function serviceGetForumPermission($iMemberId, $iForumId) {

        $iMemberId = (int)$iMemberId;
        $iForumId = (int)$iForumId;

        $aFalse = array ( // default permissions, for visitors for example
            'admin' => 0,
            'read' => 1,
            'post' => 0,
        );

        if (!($aForum = $this->_oDb->getForumById ($iForumId))) {    
			return $aFalse;
        }
  
        if (!($aDataEntry = $this->_oDb->getEntryById ($aForum['entry_id']))){
 			return $aFalse;
		}
 
        $aTrue = array (
            'admin' => $aDataEntry[$this->_oDb->_sFieldAuthorId] == $iMemberId || $this->isAdmin() ? 1 : 0, // author is admin
            'read' => $this->isAllowedPostInForum ($aDataEntry, $iMemberId) ? 1 : 0,
            'post' => $this->isAllowedPostInForum ($aDataEntry, $iMemberId) ? 1 : 0,
        );
  
        return $aTrue;
    }


    /**
     * Homepage block with different schools
     * @return html to display on homepage in a block
     */     
    function serviceHomepageBlock () {

        if (!$this->_oDb->isAnyPublicContent())
            return '';
        
		//$this->_oTemplate->addCss ('unit.css');

        bx_import ('PageMain', $this->_aModule);
        $o = new BxSchoolsPageMain ($this);
        $o->sUrlStart = BX_DOL_URL_ROOT . '?';

        $sDefaultHomepageTab = $this->_oDb->getParam('modzzz_schools_homepage_default_tab');
        $sBrowseMode = $sDefaultHomepageTab;
        switch ($_GET['modzzz_schools_filter']) {            
            case 'featured':
            case 'recent':
            case 'top':
            case 'popular':
            case $sDefaultHomepageTab:            
                $sBrowseMode = $_GET['modzzz_schools_filter'];
                break;
        }

        return $o->ajaxBrowse(
            $sBrowseMode,
            $this->_oDb->getParam('modzzz_schools_perpage_homepage'), 
            array(
                _t('_modzzz_schools_tab_featured') => array('href' => BX_DOL_URL_ROOT . '?modzzz_schools_filter=featured', 'active' => 'featured' == $sBrowseMode, 'dynamic' => true),
                _t('_modzzz_schools_tab_recent') => array('href' => BX_DOL_URL_ROOT . '?modzzz_schools_filter=recent', 'active' => 'recent' == $sBrowseMode, 'dynamic' => true),
                _t('_modzzz_schools_tab_top') => array('href' => BX_DOL_URL_ROOT . '?modzzz_schools_filter=top', 'active' => 'top' == $sBrowseMode, 'dynamic' => true),
                _t('_modzzz_schools_tab_popular') => array('href' => BX_DOL_URL_ROOT . '?modzzz_schools_filter=popular', 'active' => 'popular' == $sBrowseMode, 'dynamic' => true),
            )
        );
    }

    /**
     * Profile block with user's schools
     * @param $iProfileId profile id 
     * @return html to display on homepage in a block
     */     
    function serviceProfileBlock ($iProfileId) {
        $iProfileId = (int)$iProfileId;
        $aProfile = getProfileInfo($iProfileId);
        bx_import ('PageMain', $this->_aModule);
        $o = new BxSchoolsPageMain ($this);        
        $o->sUrlStart = getProfileLink($aProfile['ID']) . '?';

        return $o->ajaxBrowse(
            'joined', 
            $this->_oDb->getParam('modzzz_schools_perpage_profile'), 
            array(),
            process_db_input ($aProfile['NickName'], BX_TAGS_NO_ACTION, BX_SLASHES_NO_ACTION),
            true,
            false 
        );
    }

    /**
     * Profile block with user's schools
     * @param $iProfileId profile id 
     * @return html to display on homepage in a block
     */     
    function serviceSchoolMates ($iProfileId) {
        $iProfileId = (int)$iProfileId;
        $aProfile = getProfileInfo($iProfileId);
        bx_import ('PageMain', $this->_aModule);
        $o = new BxSchoolsPageMain ($this);        
        $o->sUrlStart = getProfileLink($aProfile['ID']) . '?';

        return $o->ajaxMatesBrowse(
            'school_mates', 
            $this->_oDb->getParam('modzzz_schools_perpage_profile'), 
            array(),
            process_db_input ($aProfile['NickName'], BX_TAGS_NO_ACTION, BX_SLASHES_NO_ACTION),
            true,
            false 
        );
    }

    /**
     * Profile block with schools user joied
     * @param $iProfileId profile id 
     * @return html to display on homepage in a block
     */     
    function serviceProfileBlockJoined ($iProfileId) {
        $iProfileId = (int)$iProfileId;
        $aProfile = getProfileInfo($iProfileId);
        bx_import ('PageMain', $this->_aModule);
        $o = new BxSchoolsPageMain ($this);        
        $o->sUrlStart = getProfileLink($aProfile['ID']) . '?';

        return $o->ajaxBrowse(
            'joined', 
            $this->_oDb->getParam('modzzz_schools_perpage_profile'), 
            array(),
            process_db_input ($aProfile['NickName'], BX_TAGS_NO_ACTION, BX_SLASHES_NO_ACTION),
            true,
            false 
        );
    }

    function actionConfirmAttend($iEntryId = 0) {
 
        if(! $this->_iProfileId) {
            header('location: ' . BX_DOL_URL_ROOT . 'member.php');
        }
 
		$aDataEntry = $this->_oDb->getEntryById($iEntryId);
		$sSchoolName = $aDataEntry['title'];
		$sAttendUrl = BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'confirm_attend/'.$iEntryId;
 		$sSchoolUrl = BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'view/'.$aDataEntry['uri'];

        $this->_oTemplate->pageStart();
 
		$isFan = $this->_oDb->isFan((int)$iEntryId, $this->_iProfileId, 0) || $this->_oDb->isFan((int)$iEntryId, $this->_iProfileId, 1);

	    if($isFan){
			echo MsgBox( _t("_modzzz_schools_already_fan_go_back", $sSchoolUrl) );
	    }else{
			$aForm = array(
				'form_attrs' => array(
					'name' => 'attend_form',
					'method' => 'post', 
					'action' => $sAttendUrl,
				),
				'params' => array (
					'db' => array(
						'submit_name' => 'submit_attend',
					),
				),
				'inputs' => array( 
					'id' => array(
						'name' => 'id',
						'type' => 'hidden',
						'value' => $iEntryId,
					),				
					'school_display' => array(
						'type' => 'value',
						'name' => 'school_display',
						'caption' => _t('_modzzz_school'),
						'value' => strtoupper($sSchoolName) ,  
					),   
					'year_entered' => array(
						'caption'  => _t('_modzzz_schools_caption_year_entered'),
						'info'  => _t('_modzzz_schools_info_year_entered'),
						'type'   => 'text',
						'name' => 'year_entered',
						'required' => true,
						'checker' => array (  
							'func'   => 'Xss',
							 'error'  => _t('_modzzz_schools_err_year_entered'),
						),
					),
					'year_left' => array(
						'caption'  => _t('_modzzz_schools_caption_year_left'),
						'info'  => _t('_modzzz_schools_info_year_left'),
						'type'   => 'text',
						'name' => 'year_left',
						'required' => false, 
					),

					'membership_type' => array(
						'caption'  => _t('_modzzz_schools_caption_membership_type'),
						'type'   => 'select',
						'name' => 'membership_type',
						'values' => array(
							'student'  => _t('_modzzz_schools_student'),
							'alumni'  => _t('_modzzz_schools_alumni')   
						),
						'required' => true,
						'checker' => array (  
							'func'   => 'Preg',
							'params' => array('/^[a-z]+$/'),
							'error'  => _t('_modzzz_schools_err_membership_type'),
						),
					),
					'submit' => array(
						'type'  => 'submit',
						'value' => _t('_Save'),
						'name'  => 'submit_attend',
					),
				),
			);
			$oForm = new BxTemplFormView($aForm);

			$sErrorCode = $oForm->getCode();

			$oForm->initChecker();  

			if ($oForm->isSubmittedAndValid()) { 
	 
				$sYearEntered = $oForm->getCleanValue('year_entered');
				$sYearLeft = $oForm->getCleanValue('year_left'); 
				$sMembership = $oForm->getCleanValue('membership_type');
		
				$iProcessed = $this->_oDb->addFan($iEntryId, $this->_iProfileId, $sYearEntered, $sYearLeft, $sMembership);
			  
				if($iProcessed){ 
					header('location:' . $sSchoolUrl);
				} else {
					echo $oForm->getCode(); 
				}
			}else{ 
				echo $oForm->getCode(); 
			} 

		}

        $this->_oTemplate->addCss ('main.css'); 
        $this->_oTemplate->pageCode(_t('_modzzz_schools_confirm_attendance')); 
    }


    function serviceGetMemberMenuItem () {
        parent::_serviceGetMemberMenuItem (_t('_modzzz_schools'), _t('_modzzz_schools'), 'schools.png');
    }

    function serviceGetWallPost ($aEvent) {
        return parent::_serviceGetWallPost ($aEvent, _t('_modzzz_schools_wall_object'), _t('_modzzz_schools_wall_added_new'));
    }

    function serviceGetSpyPost($sAction, $iObjectId = 0, $iSenderId = 0, $aExtraParams = array()) {
        return parent::_serviceGetSpyPost($sAction, $iObjectId, $iSenderId, $aExtraParams, array(
            'add' => '_modzzz_schools_spy_post',
            'change' => '_modzzz_schools_spy_post_change',
            'join' => '_modzzz_schools_spy_join',
            'rate' => '_modzzz_schools_spy_rate',
            'commentPost' => '_modzzz_schools_spy_comment',
        ));
    }

    function serviceGetSubscriptionParams ($sAction, $iEntryId) {

        $a = array (
            'change' => _t('_modzzz_schools_sbs_change'),
            'commentPost' => _t('_modzzz_schools_sbs_comment'),
            'rate' => _t('_modzzz_schools_sbs_rate'),
            'join' => _t('_modzzz_schools_sbs_join'),
        );

        return parent::_serviceGetSubscriptionParams ($sAction, $iEntryId, $a);
    }

    // ================================== admin actions

    function actionAdministration ($sUrl = '') {

        if (!$this->isAdmin()) {
            $this->_oTemplate->displayAccessDenied ();
            return;
        }        

        $this->_oTemplate->pageStart();

        $aMenu = array(
            'pending_approval' => array(
                'title' => _t('_modzzz_schools_menu_admin_pending_approval'), 
                'href' => BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'administration/pending_approval', 
                '_func' => array ('name' => 'actionAdministrationManage', 'params' => array(false)),
            ),
            'admin_entries' => array(
                'title' => _t('_modzzz_schools_menu_admin_entries'), 
                'href' => BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'administration/admin_entries',
                '_func' => array ('name' => 'actionAdministrationManage', 'params' => array(true)),
            ),            
            'create' => array(
                'title' => _t('_modzzz_schools_menu_admin_add_entry'), 
                'href' => BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'administration/create',
                '_func' => array ('name' => 'actionAdministrationCreateEntry', 'params' => array()),
            ),
            'settings' => array(
                'title' => _t('_modzzz_schools_menu_admin_settings'), 
                'href' => BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'administration/settings',
                '_func' => array ('name' => 'actionAdministrationSettings', 'params' => array()),
            ),
        );

        if (empty($aMenu[$sUrl]))
            $sUrl = 'pending_approval';

        $aMenu[$sUrl]['active'] = 1;
        $sContent = call_user_func_array (array($this, $aMenu[$sUrl]['_func']['name']), $aMenu[$sUrl]['_func']['params']);

        echo $this->_oTemplate->adminBlock ($sContent, _t('_modzzz_schools_page_title_administration'), $aMenu);
        $this->_oTemplate->addCssAdmin ('admin.css');
        $this->_oTemplate->addCssAdmin ('unit.css');
        $this->_oTemplate->addCssAdmin ('main.css');
        $this->_oTemplate->addCssAdmin ('forms_extra.css'); 
        $this->_oTemplate->addCssAdmin ('forms_adv.css');        
        $this->_oTemplate->pageCodeAdmin (_t('_modzzz_schools_page_title_administration'));
    }

    function actionAdministrationSettings () {
        return parent::_actionAdministrationSettings ('Schools');
    }

    function actionAdministrationManage ($isAdminEntries = false) {
        return parent::_actionAdministrationManage ($isAdminEntries, '_modzzz_schools_admin_delete', '_modzzz_schools_admin_activate');
    }

    // ================================== events


    function onEventJoinRequest ($iEntryId, $iProfileId, $aDataEntry) {
        parent::_onEventJoinRequest ($iEntryId, $iProfileId, $aDataEntry, 'modzzz_schools_join_request', BX_SCHOOLS_MAX_FANS);
    }

    function onEventJoinReject ($iEntryId, $iProfileId, $aDataEntry) {
        parent::_onEventJoinReject ($iEntryId, $iProfileId, $aDataEntry, 'modzzz_schools_join_reject');
    }

    function onEventFanRemove ($iEntryId, $iProfileId, $aDataEntry) {        
        parent::_onEventFanRemove ($iEntryId, $iProfileId, $aDataEntry, 'modzzz_schools_fan_remove');
    }

    function onEventFanBecomeAdmin ($iEntryId, $iProfileId, $aDataEntry) {        
        parent::_onEventFanBecomeAdmin ($iEntryId, $iProfileId, $aDataEntry, 'modzzz_schools_fan_become_admin');
    }

    function onEventAdminBecomeFan ($iEntryId, $iProfileId, $aDataEntry) {        
        parent::_onEventAdminBecomeFan ($iEntryId, $iProfileId, $aDataEntry, 'modzzz_schools_admin_become_fan');
    }

    function onEventJoinConfirm ($iEntryId, $iProfileId, $aDataEntry) {
        parent::_onEventJoinConfirm ($iEntryId, $iProfileId, $aDataEntry, 'modzzz_schools_join_confirm');
    }

    // ================================== permissions
    
    function isAllowedView ($aDataEntry, $isPerformAction = false) {

        // admin and owner always have access
        if ($this->isAdmin() || $aDataEntry['author_id'] == $this->_iProfileId) 
            return true;

        // check admin acl
        $this->_defineActions();
		$aCheck = checkAction($this->_iProfileId, BX_SCHOOLS_VIEW_SCHOOL, $isPerformAction);
        if ($aCheck[CHECK_ACTION_RESULT] != CHECK_ACTION_RESULT_ALLOWED)
            return false;

        // check user school 
	    return $this->_oPrivacy->check('view_school', $aDataEntry['id'], $this->_iProfileId); 
    }

    function isAllowedBrowse ($isPerformAction = false) {
        if ($this->isAdmin()) 
            return true;
        $this->_defineActions();
		$aCheck = checkAction($this->_iProfileId, BX_SCHOOLS_BROWSE, $isPerformAction);
        return $aCheck[CHECK_ACTION_RESULT] == CHECK_ACTION_RESULT_ALLOWED;
    }

    function isAllowedSearch ($isPerformAction = false) {
        if ($this->isAdmin()) 
            return true;
        $this->_defineActions();
		$aCheck = checkAction($this->_iProfileId, BX_SCHOOLS_SEARCH, $isPerformAction);
        return $aCheck[CHECK_ACTION_RESULT] == CHECK_ACTION_RESULT_ALLOWED;
    }

    function isAllowedAdd ($isPerformAction = false) {
        if ($this->isAdmin()) 
            return true;
        if (!$GLOBALS['logged']['member']) 
            return false;
        $this->_defineActions();
		$aCheck = checkAction($this->_iProfileId, BX_SCHOOLS_ADD_SCHOOL, $isPerformAction);
        return $aCheck[CHECK_ACTION_RESULT] == CHECK_ACTION_RESULT_ALLOWED;
    } 

    function isAllowedEdit ($aDataEntry, $isPerformAction = false) {

        if ($this->isAdmin() || ($GLOBALS['logged']['member'] && $aDataEntry['author_id'] == $this->_iProfileId && isProfileActive($this->_iProfileId))) 
            return true;

        // check acl
        $this->_defineActions();
		$aCheck = checkAction($this->_iProfileId, BX_SCHOOLS_EDIT_ANY_SCHOOL, $isPerformAction);
        return $aCheck[CHECK_ACTION_RESULT] == CHECK_ACTION_RESULT_ALLOWED;
    } 

    function isAllowedMarkAsFeatured ($aDataEntry, $isPerformAction = false) {
        if ($this->isAdmin()) 
            return true;
        $this->_defineActions();
        $aCheck = checkAction($this->_iProfileId, BX_SCHOOLS_MARK_AS_FEATURED, $isPerformAction);
        return $aCheck[CHECK_ACTION_RESULT] == CHECK_ACTION_RESULT_ALLOWED;        
    }

    function isAllowedBroadcast ($aDataEntry, $isPerformAction = false) {
        if ($this->isAdmin() || $this->isEntryAdmin($aDataEntry)) 
            return true;
        $this->_defineActions();
        $aCheck = checkAction($this->_iProfileId, BX_SCHOOLS_BROADCAST_MESSAGE, $isPerformAction);
        return $aCheck[CHECK_ACTION_RESULT] == CHECK_ACTION_RESULT_ALLOWED;        
    }

    function isAllowedDelete (&$aDataEntry, $isPerformAction = false) {
        if ($this->isAdmin() || ($GLOBALS['logged']['member'] && $aDataEntry['author_id'] == $this->_iProfileId && isProfileActive($this->_iProfileId))) 
            return true;
        $this->_defineActions();
		$aCheck = checkAction($this->_iProfileId, BX_SCHOOLS_DELETE_ANY_SCHOOL, $isPerformAction);
        return $aCheck[CHECK_ACTION_RESULT] == CHECK_ACTION_RESULT_ALLOWED;
    }     

    function isAllowedJoin (&$aDataEntry) {
        if (!$this->_iProfileId) 
            return false;
        return $this->_oPrivacy->check('join', $aDataEntry['id'], $this->_iProfileId);
    }

    function isAllowedSendInvitation (&$aDataEntry) {
        return $this->isAdmin() || $this->isEntryAdmin($aDataEntry) ? true : false;
    }

    function isAllowedShare (&$aDataEntry) {
        return true;
    }

    function isAllowedPostInForum(&$aDataEntry, $iProfileId = -1) {
        if (-1 == $iProfileId)
            $iProfileId = $this->_iProfileId;
        return $this->isAdmin() || $this->isEntryAdmin($aDataEntry) || $this->_oPrivacy->check('post_in_forum', $aDataEntry['id'], $iProfileId);
    }

    function isAllowedRate(&$aDataEntry) {        
        if ($this->isAdmin())
            return true;
        return $this->_oPrivacy->check('rate', $aDataEntry['id'], $this->_iProfileId);        
    }

    function isAllowedComments(&$aDataEntry) {
        if (!$this->_iProfileId) 
            return false;        
        if ($this->isAdmin())
            return true;
        return $this->_oPrivacy->check('comment', $aDataEntry['id'], $this->_iProfileId);
    }

    function isAllowedViewFans(&$aDataEntry) {
        if ($this->isAdmin())
            return true;
        return $this->_oPrivacy->check('view_fans', $aDataEntry['id'], $this->_iProfileId);
    }

    function isAllowedUploadPhotos(&$aDataEntry) {
        if (!$this->_iProfileId) 
            return false;        
        if ($this->isAdmin())
            return true;
        if (!$this->isMembershipEnabledForImages())
            return false;
        return $this->_oPrivacy->check('upload_photos', $aDataEntry['id'], $this->_iProfileId);
    }

    function isAllowedUploadVideos(&$aDataEntry) {
        if (!$this->_iProfileId) 
            return false;        
        if ($this->isAdmin())
            return true;
        if (!$this->isMembershipEnabledForVideos())
            return false;        
        return $this->_oPrivacy->check('upload_videos', $aDataEntry['id'], $this->_iProfileId);
    }

    function isAllowedUploadSounds(&$aDataEntry) {
        if (!$this->_iProfileId) 
            return false;        
        if ($this->isAdmin())
            return true;
        if (!$this->isMembershipEnabledForSounds())
            return false;                
        return $this->_oPrivacy->check('upload_sounds', $aDataEntry['id'], $this->_iProfileId);
    }

    function isAllowedUploadFiles(&$aDataEntry) {
        if (!$this->_iProfileId) 
            return false;        
        if ($this->isAdmin())
            return true;
        if (!$this->isMembershipEnabledForFiles())
            return false;                        
        return $this->_oPrivacy->check('upload_files', $aDataEntry['id'], $this->_iProfileId);
    }

    function isAllowedCreatorCommentsDeleteAndEdit (&$aDataEntry, $isPerformAction = false) {
        if ($this->isAdmin()) 
            return true;
        if (getParam('modzzz_schools_author_comments_admin') && $this->isEntryAdmin($aDataEntry))
            return true;
        $this->_defineActions();
		$aCheck = checkAction($this->_iProfileId, BX_SCHOOLS_COMMENTS_DELETE_AND_EDIT, $isPerformAction);
        return $aCheck[CHECK_ACTION_RESULT] == CHECK_ACTION_RESULT_ALLOWED;
    }

    function isAllowedManageAdmins($aDataEntry) {
        if (($GLOBALS['logged']['member'] || $GLOBALS['logged']['admin']) && $aDataEntry['author_id'] == $this->_iProfileId && isProfileActive($this->_iProfileId))
            return true;
        return false;
    }

    function isAllowedManageFans($aDataEntry) {
        return $this->isEntryAdmin($aDataEntry);
    }

    function isFan($aDataEntry, $iProfileId = 0, $isConfirmed = true) {
        if (!$iProfileId)
            $iProfileId = $this->_iProfileId;
        return $this->_oDb->isFan ($aDataEntry['id'], $iProfileId, $isConfirmed) ? true : false;
    }

    function isEntryAdmin($aDataEntry, $iProfileId = 0) {
        if (!$iProfileId)
            $iProfileId = $this->_iProfileId;
        if (($GLOBALS['logged']['member'] || $GLOBALS['logged']['admin']) && $aDataEntry['author_id'] == $iProfileId && isProfileActive($iProfileId))
            return true;
        return $this->_oDb->isGroupAdmin ($aDataEntry['id'], $iProfileId) && isProfileActive($iProfileId);
    }

    function _defineActions () {
        defineMembershipActions(array('schools view school', 'schools browse', 'schools search', 'schools add school', 'schools comments delete and edit', 'schools edit any school', 'schools delete any school', 'schools mark as featured', 'schools approve schools', 'schools broadcast message'));
    }

    function _browseMy (&$aProfile) {        
        parent::_browseMy ($aProfile, _t('_modzzz_schools_page_title_my_schools'));
    } 
	

    //[start] - ultimate schools mod from modzzz  
    function actionBroadcast ($iEntryId) {
        $this->_actionBroadcast ($iEntryId, _t('_modzzz_schools_page_title_broadcast'), _t('_modzzz_schools_msg_broadcast_no_recipients'), _t('_modzzz_schools_msg_broadcast_message_sent'));
    }

    function actionInvite ($iEntryId) {
        $this->_actionInvite ($iEntryId, 'modzzz_schools_invitation', $this->_oDb->getParam('modzzz_schools_max_email_invitations'), _t('_modzzz_schools_msg_invitation_sent'), _t('_modzzz_schools_msg_no_users_to_invite'), _t('_modzzz_schools_page_title_invite'));
    }
    function actionCalendar ($iYear = '', $iMonth = '') {

 		if($_GET['ajax']=='cal'){ 
			
			$this->_oTemplate->addCss ('main.css');
			echo $this->displayMainCalendar($iYear, $iMonth, _t('_modzzz_schools_calendar')); 
  			exit;
		} 
        parent::_actionCalendar ($iYear, $iMonth, _t('_modzzz_schools_calendar'));
    }

    function actionSearch ($sKeyword = '', $sCategory = '', $sCountry = '', $sState = '', $sCity = '', $sSchoolStart = '', $sSchoolEnd = '') {

        if (!$this->isAllowedSearch()) {
            $this->_oTemplate->displayAccessDenied ();
            return;
        }

        $this->_oTemplate->pageStart();

        if ($sKeyword) 
            $_GET['keyword'] = $sKeyword;
        if ($sCategory)
            $_GET['categories'] = explode(',', $sCategory);
        if ($sCountry)
            $_GET['country'] = explode(',', $sCountry);
		if ($sState) 
            $_GET['state'] = $sState;
		if ($sCity) 
            $_GET['city'] = $sCity;
 


        if (is_array($_GET['country']) && 1 == count($_GET['country']) && !$_GET['country'][0]) {
            unset($_GET['country']);
            unset($sCountry);
        }

        if (is_array($_GET['categories']) && 1 == count($_GET['categories']) && !$_GET['categories'][0]) {
            unset($_GET['categories']);
            unset($sCategory);
        }
 
        if ($sCountry || $sCategory || $sKeyword || $sState || $sCity ) {
            $_GET['submit_form'] = 1;  
        }
        
        modzzz_schools_import ('FormSearch');
        $oForm = new BxSchoolsFormSearch ();
        $oForm->initChecker();

        if ($oForm->isSubmittedAndValid ()) {
 
            modzzz_schools_import ('SearchResult');
            $o = new BxSchoolsSearchResult('search', $oForm->getCleanValue('Keyword'), $oForm->getCleanValue('Category'), $oForm->getCleanValue('Country'), $oForm->getCleanValue('State'), $oForm->getCleanValue('City'));

            if ($o->isError) {
                $this->_oTemplate->displayPageNotFound ();
                return;
            }

            if ($s = $o->processing()) {
                echo $s;
            } else {
                $this->_oTemplate->displayNoData ();
                return;
            }

            $this->isAllowedSearch(true); // perform search action 

            $this->_oTemplate->addCss ('unit.css');
            $this->_oTemplate->addCss ('main.css');
            $this->_oTemplate->pageCode($o->aCurrent['title'], false, false);
            return;

        } 

        echo $oForm->getCode ();
        $this->_oTemplate->addCss ('main.css');
        $this->_oTemplate->pageCode(_t('_modzzz_schools_page_title_search'));
    } 
    
    /**
     * Account block with different schools
     * @return html to display on homepage in a block
     */ 
    function serviceAccountPageBlock () {
 
        if (!$this->_oDb->isAnyPublicContent())
            return '';

		$aProfileInfo = getProfileInfo($this->_iProfileId);
		$sCity = $aProfileInfo['City'];

		if(!$sCity)
			return;

        bx_import ('PageMain', $this->_aModule);
        $o = new BxSchoolsPageMain ($this);        
        $o->sUrlStart = BX_DOL_URL_ROOT . '?';
 
        return $o->ajaxBrowse(
            'local',
            $this->_oDb->getParam('modzzz_schools_perpage_accountpage'),
			array(),
			$sCity
        );
    }

    function onSchoolCreate ($iEntryId, $sStatus, $aDataEntry = array()) {
        if ('approved' == $sStatus) {
            $this->reparseTags ($iEntryId);
            $this->reparseCategories ($iEntryId);
        }
        $this->_oDb->createForum ($aDataEntry, $this->_oDb->getProfileNickNameById($this->_iProfileId));
		
		$this->_oDb->flagActivity('add', $iEntryId, $this->_iProfileId, array('Status' => $sStatus));
		  
		$oAlert = new BxDolAlerts($this->_sPrefix, 'add', $iEntryId, $this->_iProfileId, array('Status' => $sStatus));
		$oAlert->alert();
    }

    function onSchoolChanged ($iEntryId, $sStatus) {
        $this->reparseTags ($iEntryId);
        $this->reparseCategories ($iEntryId);

		$this->_oDb->flagActivity('change', $iEntryId, $this->_iProfileId, array('Status' => $sStatus));

		$oAlert = new BxDolAlerts($this->_sPrefix, 'change', $iEntryId, $this->_iProfileId, array('Status' => $sStatus));
		$oAlert->alert();
    }    

    function onSchoolDeleted ($iEntryId, $aDataEntry = array()) {

        // delete associated tags and categories 
        $this->reparseTags ($iEntryId);
        $this->reparseCategories ($iEntryId);

        // delete votings
        bx_import('Voting', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'Voting';
        $oVoting = new $sClass ($this->_sPrefix, 0, 0);
        $oVoting->deleteVotings ($iEntryId);

        // delete comments 
        bx_import('Cmts', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'Cmts';
        $oCmts = new $sClass ($this->_sPrefix, $iEntryId);
        $oCmts->onObjectDelete ();

        // delete views
        bx_import ('BxDolViews');
        $oViews = new BxDolViews($this->_sPrefix, $iEntryId, false);
        $oViews->onObjectDelete();

        // delete forum
        $this->_oDb->deleteForum ($iEntryId);

		$this->_oDb->flagActivity('delete', $iEntryId, $this->_iProfileId);

        // arise alert
		$oAlert = new BxDolAlerts($this->_sPrefix, 'delete', $iEntryId, $this->_iProfileId);
		$oAlert->alert();
    }        

    function onEventMarkAsFeatured ($iEntryId, $aDataEntry) {
		
	$this->_oDb->flagActivity('mark_as_featured', $iEntryId, $this->_iProfileId, array('Featured' => $aDataEntry[$this->_oDb->_sFieldFeatured]));

        // arise alert
	$oAlert = new BxDolAlerts($this->_sPrefix, 'mark_as_featured', $iEntryId, $this->_iProfileId, array('Featured' => $aDataEntry[$this->_oDb->_sFieldFeatured]));
	$oAlert->alert();
    }        
 
     function actionJoin ($iEntryId, $iProfileId) {

        $this->_actionJoin ($iEntryId, $iProfileId, _t('_modzzz_schools_msg_joined_already'), _t('_modzzz_schools_msg_joined_request_pending'), _t('_modzzz_schools_msg_join_success'), _t('_modzzz_schools_msg_join_success_pending'), _t('_modzzz_schools_msg_leave_success'));
    }   
 
    function _actionJoin ($iEntryId, $iProfileId, $sMsgAlreadyJoined, $sMsgAlreadyJoinedPending, $sMsgJoinSuccess, $sMsgJoinSuccessPending, $sMsgLeaveSuccess) {

        $iEntryId = (int)$iEntryId;
        if (!($aDataEntry = $this->_oDb->getEntryByIdAndOwner($iEntryId, 0, true))) {
            echo MsgBox(_t('_sys_request_page_not_found_cpt')) . genAjaxyPopupJS($iEntryId, 'ajaxy_popup_result_div');
            exit;
        }

        if (!$this->isAllowedJoin($aDataEntry) || 0 != strcasecmp($_SERVER['REQUEST_METHOD'], 'POST')) {
            echo MsgBox(_t('_Access denied')) . genAjaxyPopupJS($iEntryId, 'ajaxy_popup_result_div');
            exit;
        }

		$isFan = $this->_oDb->isFan ($iEntryId, $this->_iProfileId, true) || $this->_oDb->isFan ($iEntryId, $this->_iProfileId, false);

		if ($isFan) {

			if ($this->_oDb->leaveEntry($iEntryId, $this->_iProfileId)) {
				
				$this->_oDb->flagActivity('unjoin', $iEntryId, $this->_iProfileId);
		  
				$sRedirect = BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'view/' . $aDataEntry[$this->_oDb->_sFieldUri];
				echo MsgBox($sMsgLeaveSuccess) . genAjaxyPopupJS($iEntryId, 'ajaxy_popup_result_div', $sRedirect);
				exit;
			}

		} else {
		
			$isConfirmed = ($this->isEntryAdmin($aDataEntry) || !$aDataEntry[$this->_oDb->_sFieldJoinConfirmation] ? true : false);

			if ($this->_oDb->joinEntry($iEntryId, $this->_iProfileId, $isConfirmed)) {
				if ($isConfirmed) {
					
					$this->_oDb->flagActivity('join', $iEntryId, $this->_iProfileId);
		 
					$this->onSchoolJoin ($iEntryId, $this->_iProfileId, $aDataEntry);
					$sRedirect = BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'view/' . $aDataEntry[$this->_oDb->_sFieldUri];
				} else {
					$this->onSchoolJoinRequest ($iEntryId, $this->_iProfileId, $aDataEntry);
					$sRedirect = '';
				}            
				echo MsgBox($isConfirmed ? $sMsgJoinSuccess : $sMsgJoinSuccessPending) . genAjaxyPopupJS($iEntryId, 'ajaxy_popup_result_div', $sRedirect);
				exit;
			}
		}

        echo MsgBox(_t('_Error Occured')) . genAjaxyPopupJS($iEntryId, 'ajaxy_popup_result_div');
        exit;
    }    
 
    function _onSchoolFanRemove ($iEntryId, $iProfileId, $aDataEntry, $sEmailTemplate) {
        
		$this->_oDb->flagActivity('unjoin', $iEntryId, $iProfileId);
		
		$this->_notifyEmail ($sEmailTemplate, $iProfileId, $aDataEntry);
		$oAlert = new BxDolAlerts($this->_sPrefix, 'fan_remove', $iEntryId, $iProfileId);
		$oAlert->alert();        
    }

    function _onSchoolFanBecomeAdmin ($iEntryId, $iProfileId, $aDataEntry, $sEmailTemplate) {
        
		$this->_oDb->flagActivity('makeAdmin', $iEntryId, $iProfileId);
	
		$this->_notifyEmail ($sEmailTemplate, $iProfileId, $aDataEntry);
		$oAlert = new BxDolAlerts($this->_sPrefix, 'fan_become_admin', $iEntryId, $iProfileId);
		$oAlert->alert();        
    }

    function _onSchoolAdminBecomeFan ($iEntryId, $iProfileId, $aDataEntry, $sEmailTemplate) {
        
		$this->_oDb->flagActivity('removeAdmin', $iEntryId, $iProfileId);
		 
		$this->_notifyEmail ($sEmailTemplate, $iProfileId, $aDataEntry);
		$oAlert = new BxDolAlerts($this->_sPrefix, 'admin_become_fan', $iEntryId, $iProfileId);
		$oAlert->alert();        
    }

    function _onSchoolJoinConfirm ($iEntryId, $iProfileId, $aDataEntry, $sEmailTemplate) {
        
		$this->_oDb->flagActivity('join', $iEntryId, $this->_iProfileId);
		
		$this->_notifyEmail ($sEmailTemplate, $iProfileId, $aDataEntry);
		$oAlert = new BxDolAlerts($this->_sPrefix, 'join_confirm', $iEntryId, $iProfileId);
		$oAlert->alert();        
    }


    function actionLocal ($sCountry='', $sState='') { 
        $this->_oTemplate->pageStart();
        bx_import ('PageLocal', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'PageLocal';
        $oPage = new $sClass ($this, $sCountry, $sState);
        echo $oPage->getCode();
        $this->_oTemplate->addCss ('main.css');
        $this->_oTemplate->addCss ('unit.css');
         $this->_oTemplate->pageCode(_t('_modzzz_schools_page_title_local'), false, false);
    } 

    function _actionBroadcast ($iEntryId, $sTitle, $sMsgNoRecipients, $sMsgSent) {
		global $tmpl;
		require_once( BX_DIRECTORY_PATH_ROOT . 'templates/tmpl_' . $tmpl . '/scripts/BxTemplMailBox.php');

        $iEntryId = (int)$iEntryId;
        if (!($aDataEntry = $this->_oDb->getEntryById($iEntryId))) {
            $this->_oTemplate->displayPageNotFound ();
            return;
        }

        if (!$this->isAllowedBroadcast($aDataEntry)) {
            $this->_oTemplate->displayAccessDenied ();
            return;
        }

        $this->_oTemplate->pageStart();

        $GLOBALS['oTopMenu']->setCustomSubHeader($aDataEntry[$this->_oDb->_sFieldTitle]);
        $GLOBALS['oTopMenu']->setCustomVar($this->_sPrefix.'_view_uri', $aDataEntry[$this->_oDb->_sFieldUri]);

		if(!(($GLOBALS['site']['ver']=='7.0') && ($GLOBALS['site']['build']=='0'))) {  		
			$GLOBALS['oTopMenu']->setCustomBreadcrumbs(array(
				_t('_'.$this->_sPrefix) => BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'home/',
				$aDataEntry[$this->_oDb->_sFieldTitle] => BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'view/' . $aDataEntry[$this->_oDb->_sFieldUri],
				$sTitle => '',
			));
		}

        $aRecipients = $this->_oDb->getBroadcastRecipients ($iEntryId);
        if (!$aRecipients) {
            echo MsgBox ($sMsgNoRecipients);
            $this->_oTemplate->pageCode($sMsgNoRecipients, true, true);
            return;
        }

        bx_import ('FormBroadcast', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'FormBroadcast';
        $oForm = new $sClass ();
        $oForm->initChecker();

        if ($oForm->isSubmittedAndValid ()) {
            
            $oEmailTemplate = new BxDolEmailTemplates();
            if (!$oEmailTemplate) {
                $this->_oTemplate->displayErrorOccured();
                return;
            }
            $aTemplate = $oEmailTemplate->getTemplate($this->_sPrefix . '_broadcast'); 
            $aTemplateVars = array (
                'BroadcastTitle' => $oForm->getCleanValue ('title'),
                'BroadcastMessage' => $oForm->getCleanValue ('message'),
                'EntryTitle' => $aDataEntry[$this->_oDb->_sFieldTitle],
                'EntryUrl' => BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'view/' . $aDataEntry[$this->_oDb->_sFieldUri],                
            );
  
            $iSentMailsCounter = 0;            
            foreach ($aRecipients as $aProfile) {		        
       	        $iSentMailsCounter += sendMail($aProfile['Email'], $aTemplate['Subject'], $aTemplate['Body'], $aProfile['id'], $aTemplateVars);

				$this->broadCastToInbox($aProfile, $aTemplate, $aTemplateVars);  
            }
            if (!$iSentMailsCounter) {
                $this->_oTemplate->displayErrorOccured();
                return;
            }

            echo MsgBox ($sMsgSent);

            $this->isAllowedBroadcast($aDataEntry, true); // perform send broadcast message action             
            $this->_oTemplate->addCss ('main.css');
            $this->_oTemplate->pageCode($sMsgSent, true, true);
            return;
        } 

        echo $oForm->getCode ();

        $this->_oTemplate->addCss ('main.css');
        $this->_oTemplate->pageCode($sTitle);
    }

    function _actionInvite ($iEntryId, $sEmailTemplate, $iMaxEmailInvitations, $sMsgInvitationSent, $sMsgNoUsers, $sTitle) {
		global $tmpl;
		require_once( BX_DIRECTORY_PATH_ROOT . 'templates/tmpl_' . $tmpl . '/scripts/BxTemplMailBox.php');

        $iEntryId = (int)$iEntryId;
        if (!($aDataEntry = $this->_oDb->getEntryByIdAndOwner($iEntryId, $this->_iProfileId, $this->isAdmin()))) {
            $this->_oTemplate->displayPageNotFound ();
            return;
        }

        $this->_oTemplate->pageStart();

        $GLOBALS['oTopMenu']->setCustomSubHeader($aDataEntry[$this->_oDb->_sFieldTitle]);
        $GLOBALS['oTopMenu']->setCustomVar($this->_sPrefix.'_view_uri', $aDataEntry[$this->_oDb->_sFieldUri]);

		if(!(($GLOBALS['site']['ver']=='7.0') && ($GLOBALS['site']['build']=='0'))) { 
			$GLOBALS['oTopMenu']->setCustomBreadcrumbs(array(
				_t('_'.$this->_sPrefix) => BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'home/',
				$aDataEntry[$this->_oDb->_sFieldTitle] => BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'view/' . $aDataEntry[$this->_oDb->_sFieldUri],
				$sTitle . $aDataEntry[$this->_oDb->_sFieldTitle] => '',
			));
		}

        bx_import('BxDolTwigFormInviter');
        $oForm = new BxDolTwigFormInviter ($this, $sMsgNoUsers);
        $oForm->initChecker();

        if ($oForm->isSubmittedAndValid ()) {        

            $aInviter = getProfileInfo($this->_iProfileId);
            $aPlusOriginal = $this->_getInviteParams ($aDataEntry, $aInviter);
            
            $oEmailTemplate = new BxDolEmailTemplates();
            $aTemplate = $oEmailTemplate->getTemplate($sEmailTemplate);
            $iSuccess = 0;

            // send invitation to registered members
            if (false !== bx_get('inviter_users') && is_array(bx_get('inviter_users'))) {
				$aInviteUsers = bx_get('inviter_users');
                foreach ($aInviteUsers as $iRecipient) {
                    $aRecipient = getProfileInfo($iRecipient);
                    $aPlus = array_merge (array ('NickName' => ' ' . $aRecipient['NickName']), $aPlusOriginal);
                    $iSuccess += sendMail(trim($aRecipient['Email']), $aTemplate['Subject'], $aTemplate['Body'], '', $aPlus) ? 1 : 0;

					$this->inviteToInbox($aRecipient, $aTemplate, $aPlusOriginal); 
                }
            }

            // send invitation to additional emails
            $iMaxCount = $iMaxEmailInvitations;
            $aEmails = preg_split ("#[,\s\\b]+#", bx_get('inviter_emails'));
            $aPlus = array_merge (array ('NickName' => ''), $aPlusOriginal);
            if ($aEmails && is_array($aEmails)) {
                foreach ($aEmails as $sEmail) {
                    if (strlen($sEmail) < 5) 
                        continue;
                    $iRet = sendMail(trim($sEmail), $aTemplate['Subject'], $aTemplate['Body'], '', $aPlus) ? 1 : 0;
                    $iSuccess += $iRet;
                    if ($iRet && 0 == --$iMaxCount) 
                        break;
                }             
            }

            $sMsg = sprintf($sMsgInvitationSent, $iSuccess);
            echo MsgBox($sMsg);
            $this->_oTemplate->addCss ('main.css');
            $this->_oTemplate->pageCode ($sMsg, true, false);
            return;
        } 

        echo $oForm->getCode ();
        $this->_oTemplate->addCss ('main.css');
        $this->_oTemplate->addCss ('inviter.css');
        $this->_oTemplate->pageCode($sTitle . $aDataEntry[$this->_oDb->_sFieldTitle]);
    }

    function  inviteToInbox($aProfile, $aTemplate, $aPlusOriginal){
	
	$aMailBoxSettings = array
	(
		'member_id'	 =>  $this->_iProfileId, 
		'recipient_id'	 => $aProfile['ID'], 
		'messages_types'	 =>  'mail',  
	);

	$aComposeSettings = array
	(
		'send_copy' => false , 
		'send_copy_to_me' => false , 
		'notification' => false ,
	);
	$oMailBox = new BxTemplMailBox('mail_page', $aMailBoxSettings);

	$sMessageBody = $aTemplate['Body'];
	$sMessageBody = str_replace("<SchoolName>", $aPlusOriginal['SchoolName'] , $sMessageBody);
	$sMessageBody = str_replace("<SchoolLocation>", $aPlusOriginal['SchoolLocation'] , $sMessageBody);
	$sMessageBody = str_replace("<SchoolUrl>", $aPlusOriginal['SchoolUrl'] , $sMessageBody);
	$sMessageBody = str_replace("<InviterUrl>", $aPlusOriginal['InviterUrl'] , $sMessageBody);
	$sMessageBody = str_replace("<InviterNickName>", $aPlusOriginal['InviterNickName'] , $sMessageBody);
	$sMessageBody = str_replace("<InvitationText>", $aPlusOriginal['InvitationText'] , $sMessageBody);

	$oMailBox -> sendMessage($aTemplate['Subject'], $sMessageBody, $aProfile['ID'], $aComposeSettings); 

   }

   function  broadCastToInbox($aProfile, $aTemplate, $aTemplateVars){

	$aMailBoxSettings = array
	(
		'member_id'	 =>  $this->_iProfileId, 
		'recipient_id'	 => $aProfile['ID'], 
		'messages_types'	 =>  'mail',  
	);

	$aComposeSettings = array
	(
		'send_copy' => false , 
		'send_copy_to_me' => false , 
		'notification' => false ,
	);
	$oMailBox = new BxTemplMailBox('mail_page', $aMailBoxSettings);

	$sMessageBody = $aTemplate['Body'];
	$sMessageBody = str_replace("<NickName>", getNickName($this->_iProfileId), $sMessageBody);
	$sMessageBody = str_replace("<EntryUrl>", $aTemplateVars['EntryUrl'], $sMessageBody);
	$sMessageBody = str_replace("<EntryTitle>", $aTemplateVars['EntryTitle'], $sMessageBody);
	$sMessageBody = str_replace("<BroadcastMessage>", $aTemplateVars['BroadcastMessage'], $sMessageBody);

	$oMailBox -> sendMessage($aTemplateVars['BroadcastTitle'], $sMessageBody, $aProfile['ID'], $aComposeSettings); 

    }

    function parseTags($s)
    {
        return $this->_parseAnything($s, ',', BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'browse/tag/');
    }

    function parseCategories($s)
    {
        return $this->_parseAnything($s, CATEGORIES_DIVIDER, BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'browse/category/');
    }

    function _parseAnything($s, $sDiv, $sLinkStart, $sClassName = '')
    {
        $sRet = '';
        $a = explode ($sDiv, $s);
        $sClass = $sClassName ? 'class="'.$sClassName.'"' : '';
        
        foreach ($a as $sName)
            $sRet .= '<a '.$sClass.' href="' . $sLinkStart . urlencode(title2uri($sName)) . '">'.$sName.'</a>&#160';
        
        return $sRet;
    } 

    function displayMainCalendar($iYear, $iMonth, $sTitle) {
    
        $this->_oTemplate->pageStart();
 
        bx_import ('Calendar', $this->_aModule);
        $oCalendar = bx_instance ($this->_aModule['class_prefix'] . 'Calendar', array ($iYear, $iMonth, $this->_oDb, $this->_oTemplate, $this->_oConfig));
  
        $aVars = array (
            'bx_repeat:week_names' => $oCalendar->_getWeekNames (),
            'bx_repeat:calendar_row' => $oCalendar->_getCalendar (),
            'month_prev_url' => $oCalendar->getBaseUri () . "{$oCalendar->iPrevYear}/{$oCalendar->iPrevMonth}&ajax=cal",
            'month_prev_name' => _t('_month_prev'),
            'month_prev_icon' => getTemplateIcon('sys_back.png'),
            'month_next_url' => $oCalendar->getBaseUri () . "{$oCalendar->iNextYear}/{$oCalendar->iNextMonth}&ajax=cal",
            'month_next_name' => _t('_month_next'),
            'month_next_icon' => getTemplateIcon('sys_next.png'),
            'month_current' => $oCalendar->getTitle(),
        );
        $sHtml = $this->_oTemplate->parseHtmlByName('main_calendar', $aVars);
        $sHtml = preg_replace ('#<bx_repeat:schools>.*?</bx_repeat:schools>#s', '', $sHtml);
        $this->_oTemplate->addCss('calendar.css');
        
	return $sHtml;
    } 
    //[end] - ultimate schools mod from modzzz 
 






}

?>
